package com.scut.campus.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.scut.campus.context.BaseContext;
import com.scut.campus.dto.PageDTO;
import com.scut.campus.entity.Post;
import com.scut.campus.mapper.PostMapper;
import com.scut.campus.query.PostQuery;
import com.scut.campus.query.base.PageQuery;
import com.scut.campus.service.PostService;
import com.scut.campus.vo.PostVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class PostServiceImpl extends ServiceImpl<PostMapper, Post> implements PostService {
    @Autowired
    private PostMapper postMapper;

    @Override
    public void visitPost(String postId) {
        LambdaUpdateWrapper<Post> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper
                .eq(Post::getPostId, postId)
                .setSql("visit_num =visit_num + 1");
        this.update(lambdaUpdateWrapper);
    }

    @Override
    public PageDTO<Post> queryMyPost(PageQuery pageQuery) {
        LambdaQueryWrapper<Post> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Post::getUserId, BaseContext.getCurrentId());
        Page<Post> page = pageQuery.toMpPageDefaultSortByCreateTimeDesc();
        page(page, lambdaQueryWrapper);
        return PageDTO.of(page, Post.class);
    }

    @Override
    public List<PostVo> queryMainPost(PostQuery postQuery) {
        return postMapper.queryMainPost(postQuery);
    }

    @Override
    public Post getSinglePost(String postId) {
        LambdaQueryWrapper<Post> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Post::getPostId, postId);
        return this.getOne(lambdaQueryWrapper);
    }

    @Override
    public void likePost(String postId) {
        LambdaUpdateWrapper<Post> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper
                .eq(Post::getPostId, postId)
                .setSql("like_num = like_num + 1");
        this.update(lambdaUpdateWrapper);
    }

    @Override
    public void dislikePost(String postId) {
        LambdaUpdateWrapper<Post> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper
                .eq(Post::getPostId, postId)
                .setSql("like_num = like_num - 1");
        this.update(lambdaUpdateWrapper);
    }


}
